package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
/**
 * 获取售货机故障,自动创建运维工单,并派发给,工单数最少人员
 */
public class VMStatusHandler implements MsgHandler {


    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;


    @Override
    public void process(String jsonMsg) throws IOException {
        //参数效验
        if (jsonMsg == null) {
            log.error("创建自动维修工单失败，msg is:"+jsonMsg);

        }
        //获取协议对象
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //根据售货机编号查询售货机
        String innerCode = vmStatusContract.getInnerCode();
        VmVO vmInfo = vmService.getVMInfo(innerCode);


        List<StatusInfo> statusInfoList = vmStatusContract.getStatusInfo();
        boolean flag = statusInfoList.stream()
                //集合内有元素满足下面条件
                .anyMatch(statusInfo ->
                        //售货机状态码,不正常
                        statusInfo.isStatus() == false);
        if (flag) {
            try {

            TaskViewModel taskViewModel = new TaskViewModel();
            //获取最少工单数员工
            int leastUserId = taskService.getLeastUser(vmInfo.getRegionId(), true);
            //执行人Id
            taskViewModel.setUserId(leastUserId);
            taskViewModel.setDesc("自动维修工单");
            taskViewModel.setInnerCode(innerCode);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);//维修工单
            taskViewModel.setCreateType(0);//自动工单
            taskService.addTask(taskViewModel);
            }catch (Exception e){
                log.error("创建自动维修工单失败，msg is:"+jsonMsg);
            }


        }


    }

}
